package com.woniuxy.qiantai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.qiantai.entity.Book;
import com.woniuxy.qiantai.entity.Item;
import com.woniuxy.qiantai.entity.Order;
import com.woniuxy.qiantai.entity.User;
import com.woniuxy.qiantai.mapper.BookMapper;
import com.woniuxy.qiantai.mapper.ItemMapper;
import com.woniuxy.qiantai.mapper.OrderMapper;
import com.woniuxy.qiantai.service.MyCartService;
import com.woniuxy.qiantai.service.OrderService;
import com.woniuxy.qiantai.vo.CartItem;
import com.woniuxy.qiantai.vo.CartOrder;
import com.woniuxy.qiantai.vo.OrderItem;
import com.woniuxy.qiantai.vo.OrderVo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author woniumrwang
 * @since 2023-01-06 02:44:36
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    RedisTemplate<String,Object> stringObjectRedisTemplate;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    MyCartService myCartService;

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    BookMapper bookMapper;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public CartOrder getCartOrder(Long userId, Long[] bookIds) {

        HashOperations<String, Object, Object> hashOperations = stringObjectRedisTemplate.opsForHash();
        List<Object> allCartItems = hashOperations.values(userId + "");

        CartOrder cartOrder = new CartOrder();
        cartOrder.setCartItems(new ArrayList<>());

        //计算总价
        BigDecimal totalPrice = new BigDecimal("0.00");
        for(Object item : allCartItems){
            CartItem cartItem = (CartItem)item;
            for(Long bookId : bookIds){
                //只有当前项的id在bookIds中时才作为计算总价的一部分
                //同时拿到要结算的cartItem
                if (cartItem.getBookId().equals(bookId)){
                    cartOrder.getCartItems().add(cartItem);
                    totalPrice = totalPrice.add(cartItem.getSumPrice());
                }
            }
        }

        cartOrder.setTotalPrice(totalPrice);

        return cartOrder;
    }

    @Override
    @Transactional
    public void createOrder(User currentUser, Long[] bookIds, Integer addressId) {

        //获取要结算项目的详情
        CartOrder cartOrder = getCartOrder(currentUser.getId(), bookIds);

        //创建一个订单出来
        //订单表Order中新增订单
        Order order = new Order();
        String orderNum = "WONIU"+new Date().getTime();
        order.setOrderNum(orderNum);
//        order.setTotalprice(myCartService.calTotalPrice(currentUser.getId(),bookIds));
        order.setTotalprice(cartOrder.getTotalPrice());
        order.setUserId(currentUser.getId());
        order.setAddressId(addressId.longValue());  //addressId需要转换为logn值
        order.setCreatetime(new Date());
        order.setState(1);  //订单状态 1.未支付  2 . 已支付  3.退款中  4. 已退款  5.已取消

        int num = orderMapper.insert(order);
        System.out.println(num);
        System.out.println(order.getId());

        //存储订单详情
        List<CartItem> cartItems = cartOrder.getCartItems();

//        for(Long bookId : bookIds){
//            Item item = new Item();
//            item.setBookId(bookId);
//        }

        for (CartItem cartItem : cartItems){
            Item item = new Item();
            item.setBookId(cartItem.getBookId());
            item.setBookName(cartItem.getBookName());
            item.setPrice(cartItem.getBookPrice());
            item.setBcount(cartItem.getItemNum());
            item.setSumprice(cartItem.getSumPrice());
            item.setOrderId(order.getId());
            item.setCreatetime(new Date());
            item.setState(1);  //订单项状态,我们这里取默认值1

            itemMapper.insert(item);

            //更新图书的库存和购买量
            int updateNum = bookMapper.updateBookStoreCount(cartItem.getBookId(), cartItem.getItemNum());
            if (updateNum<1){
                throw new RuntimeException("库存量不足,下单失败");
            }
            bookMapper.updateBuyCount(cartItem.getBookId(),cartItem.getItemNum());

            //已经结算的图书要从购物车中清除掉
            myCartService.updateItemNum(currentUser.getId(),cartItem.getBookId(),0);

        }

        //发送一个mq消息,15分钟后消费者需要检查该订单是否已支付,未支付订单需要被取消掉
        //消息生产者
        rabbitTemplate.convertAndSend("cancleOrderNoramlExchange","delayCancelOrder",order.getId());

        //发送消息的同时自定义消息的ttl
//        rabbitTemplate.convertAndSend("cancleOrderNoramlExchange", "delayCancelOrder", order.getId(), new MessagePostProcessor() {
//            @Override
//            public Message postProcessMessage(Message message) throws AmqpException {
//                message.getMessageProperties().setExpiration("15000");  //配置消息的ttl
//                return message;
//            }
//        });

    }

    @Override
    public List<OrderVo> queryAllOrder(Long userId) {

        List<OrderVo> orderVoList = new ArrayList<>();

        //读取订单信息
        // Query Wrapper 组装查询条件
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",userId);
        queryWrapper.orderByDesc("createtime");

        List<Order> orderList = orderMapper.selectList(queryWrapper);
        for(Order order : orderList){

            OrderVo orderVo = new OrderVo();
            orderVo.setId(order.getId());
            orderVo.setOrderNum(order.getOrderNum());
            orderVo.setOrderTime(order.getCreatetime());
            orderVo.setTotalPrice(order.getTotalprice());
            orderVo.setState(order.getState());

            //查询订单项具体信息
            QueryWrapper<Item> itemQueryWrapper = new QueryWrapper<>();
            itemQueryWrapper.eq("orderId",order.getId());
            List<Item> itemList = itemMapper.selectList(itemQueryWrapper);
            //Lambda语法, 不太能理解的话,还用For循环去实现.
            List<OrderItem> orderItemList = itemList.stream()
                    .map(item -> {
                        OrderItem orderItem = new OrderItem();

                        //查询图书的图片地址
                        Book book = bookMapper.selectById(item.getBookId());
                        orderItem.setImgSrc(book.getImgsrc());

                        orderItem.setBookName(item.getBookName());
                        orderItem.setBuyCount(item.getBcount());
                        orderItem.setSumPrice(item.getSumprice());

                        return orderItem;
                    })
                    .collect(Collectors.toList());

            orderVo.setOrderItemList(orderItemList);

            orderVoList.add(orderVo);
        }


        return orderVoList;
    }

    @Override
    public void updateState(Long orderId, Integer newState) {

        orderMapper.updateState(orderId,newState);

    }

}
